package com.zhang.list;

import java.util.Arrays;

/**
 * @author zhang
 * @time 2022/03/19 09:42:05
 */
public class LinkedList {
    private class Node {
        private int value;
        private Node next;

        public Node(int value) {
            this.value = value;
        }
    }

    private Node first;
    private Node last;
    private int size;

    public void addLast(int item) {
        Node node = new Node(item);

        if (isEmpty()) {
            first = last = node;
        }        else {
            last.next = node;
            last = node;
        }

        size++;
    }

    private boolean isEmpty() {
        return first == null;
    }
    public void printMiddle() {
        Node a = first;
        Node b = first;
        while (b != last && b.next != last) {
            b = b.next.next;
            a = a.next;
        }
        if (b == last) {
            System.out.println(a.value);

        } else {
            System.out.println(a.value + ": " + a.next.value);
        }
    }
    public void reverse() {
        if (isEmpty()) {
            return;
        }

        Node previous = first;
        Node current = first.next;
        while (current != null) {
            Node next = current.next;
            current.next = previous;
            previous = current;
            current = next;
        }

        last = first;
        last.next = null;
        first = previous;

    }

   public int[] toArray() {
       int[] array = new int[size];

       Node current = first;
       int index = 0;
       while (current != null) {
           array[index++] = current.value;
           current = current.next;
       }
       return array;
   }

    public int getKthFromEnd(int k) {
        Node a = first;
        Node b = first;
        for (int i = 0; i < k - 1; i++) {
            b = b.next;
            if (b == null) {
                throw new IllegalArgumentException();
            }
        }
        while (b != last) {
            a = a.next;
            b = b.next;
        }
        return a.value;

    }

    public boolean hasLoop() {
        Node slow = first;
        Node fast = first;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;

        }
        if (slow == fast) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.addLast(1);
        list.addLast(2);
        list.addLast(3);
        list.addLast(4);
        list.addLast(5);
        list.addLast(6);
        list.reverse();

        System.out.println(Arrays.toString(list.toArray()));


    }
}
